package com.gzbsoft.sc.modules.sys.service.impl;
import cn.hutool.core.util.ReflectUtil;
import com.gzbsoft.sc.modules.sys.dao.BaseDao;
import com.gzbsoft.sc.modules.sys.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.stream.Stream;
@SuppressWarnings("unchecked")
public abstract class BaseServiceImpl<T, ID> implements BaseService<T, ID> {
    @Autowired
    private BaseDao baseDao;
    private Class clazz;
    private T instance;
    public BaseServiceImpl() {
        Type type = this.getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) type;
            Type[] tps = pt.getActualTypeArguments();
            if (tps.length > 0) {
                this.clazz = (Class) tps[0];
                this.instance = (T) ReflectUtil.newInstance(clazz);
            }
        }
    }
    @Override
    public List<T> list(T t) {
        return baseDao.findAll(Example.of(t));
    }
    @Override
    public Page<T> page(T t, @NotNull Pageable page) {
        if (t == null) {
            t = instance;
        }
        return baseDao.findAll(Example.of(t), page);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public T save(T t) {
        baseDao.save(t);
        return t;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public T update(T t) {
        baseDao.update(t);
        return t;
    }
    @Override
    public void deleteBatch(ID[] ids) {
        Stream.of(ids).forEach(baseDao::deleteById);
    }
    @Override
    public void deleteById(ID menuId) {
        baseDao.deleteById(menuId);
    }
}
